package com.yourenbang.lingyun.transaction.web.service.impl.fund;

import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundBillMapper;
import com.yourenbang.lingyun.transaction.web.domain.po.FundBill;
import com.yourenbang.transaction.api.model.dto.AddBillDTO;
import com.yourenbang.transaction.api.service.fund.FundBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * 账单服务
 */
@Slf4j
@RestController
public class FundBillServiceImpl implements FundBillService {

    @Autowired
    private TransactionFundBillMapper fundBillMapper;

    /**
     * 记录账单
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result<Void> addBill(AddBillDTO dto) {

        LocalDateTime now = LocalDateTime.now();
        FundBill bill = new FundBill(dto.getPlatNo());
        bill.setUserBaseId(dto.getUserBaseId());
        bill.setFundAccountId(dto.getFundAccountId());
        bill.setFundAccountChangePlanId(dto.getFundAccountChangePlanId());
        bill.setOrderId(dto.getOrderId());
        bill.setAmount(dto.getAmount());
        bill.setType(dto.getBillType().getType());
        bill.setFundTypeName(dto.getBillType().getName());
        bill.setDetail(dto.getDetail());
        bill.setTransactionMonth(DateFormat.DATE_MONTH.format(now));
        bill.setTransactionDay(DateFormat.DATE_COMPACT.format(now));
        bill.setShowFlag(dto.getShowFlag() == null || dto.getShowFlag());
        bill.setChannelId(dto.getChannelId());
        bill.setPlatNo(dto.getPlatNo());
        if (dto.getManualFlag() != null) {
            bill.setManualFlag(dto.getManualFlag());
        }
        if (StringUtils.isNotBlank(dto.getOperator())) {
            bill.setOperator(dto.getOperator());
        }

        bill.setAccountMainJournalType(dto.getAccountMainJournalType());
        bill.setAccountMainJournalTypeName(dto.getAccountMainJournalTypeName());

        int inertCount = fundBillMapper.insert(bill);
        BizAssertUtils.assertOne(inertCount, "记录账单失败");
        return Result.builder().success();
    }
}
